package org.ztest.zip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZIPTest
{
    public byte[] compress(byte[] plainData) throws IOException
    {
        try (ByteArrayOutputStream bao = new ByteArrayOutputStream())
        {
            ZipOutputStream zip = new ZipOutputStream(bao);
            zip.putNextEntry(new ZipEntry(""));
            zip.write(plainData);
            zip.close();
            return bao.toByteArray();
        }
    }
    
    public byte[] deCompress(byte[] cipherData) throws IOException
    {
        try (ByteArrayInputStream bai = new ByteArrayInputStream(cipherData);
                ByteArrayOutputStream bao = new ByteArrayOutputStream())
           {
               ZipInputStream zip = new ZipInputStream(bai);
               zip.getNextEntry();
               byte[] buf = new byte[128];
               int n = 0;
               while ((n = zip.read(buf)) > 0)
               {
                   bao.write(buf, 0, n);
               }
               return bao.toByteArray();
           }
    }
}
